<template>
  <a-card class="general-card" title="支付设置" :bordered="false">
    <a-tabs :default-active-key="payFormData.payType" @change="clickpatTab">
      <a-tab-pane key="PAYMENT_SUPPORT" title="支付开启/关闭">
        <a-col style="margin-bottom: 10px">
          <a-space
            v-for="(item, index) in payFormData.paymentSupportForm"
            :key="index"
          >
            <div bordered class="auth-item">
              <div class="icon-item">
                <img v-if="item.client === 'APP'" class="icon" :src="getAssetsImages('app.svg')" alt=""/>
                <img v-if="item.client === 'H5'" class="icon" :src="getAssetsImages('h5.svg')" alt=""/>
                <img v-if="item.client === 'WECHAT_MP'" class="icon" :src="getAssetsImages('wechat_mp.svg')" alt=""/>
                <img v-if="item.client === 'PC'" class="icon" :src="getAssetsImages('pc.svg')" alt=""/>
              </div>
              <div class="pay-title">{{ payFormData.way[item.client] }}</div>
              <a-divider
                orientation="left"
                :style="{ marginTop: '30px', marginBottom: '30px' }"
                >支付设置</a-divider
              >
              <div :key="componentKey" class="pay-list">
                <a-checkbox-group
                  v-model="item.supports"
                  :default-value="item.supports"
                  @change="handleChangePayType"
                  
                >
                  <a-checkbox
                    v-for="(item, index) in payFormData.supportForm.payments"
                    :key="index"
                    :value="item"
                   
                    >{{ payFormData.payWay[item] || item }}</a-checkbox
                  >
                </a-checkbox-group>
              </div>
            </div>
          </a-space>
        </a-col>
      </a-tab-pane>
      <a-tab-pane key="ALIPAY_PAYMENT" title="支付宝支付设置">
        <a-col :span="10">
          <a-form
            ref="alipayFormRef"
            :model="payFormData.alipayForm"
            :style="{ width: '100%' }"
            layout="horizontal"
            auto-label-width
          >
            <a-form-item label="appId" field="appId" :rules="[REQUIRED]">
              <a-input
                v-model="payFormData.alipayForm.appId"
                type="text"
                placeholder=""
              />
            </a-form-item>
            <a-form-item label="certPath" field="certPath" :rules="[REQUIRED]">
              <a-input
                v-model="payFormData.alipayForm.certPath"
                type="text"
                placeholder=""
              />
            </a-form-item>
            <a-form-item
              label="alipayPublicCertPath"
              field="alipayPublicCertPath"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="payFormData.alipayForm.alipayPublicCertPath"
                type="text"
                placeholder=""
              />
            </a-form-item>
            <a-form-item
              label="privateKey"
              field="privateKey"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="payFormData.alipayForm.privateKey"
                type="text"
                placeholder=""
              />
            </a-form-item>
            <a-form-item
              label="rootCertPath"
              field="rootCertPath"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="payFormData.alipayForm.rootCertPath"
                type="text"
                placeholder=""
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="alipayFormSubmit">保存</a-button>
            </a-form-item>
          </a-form>
        </a-col>
      </a-tab-pane>
      <a-tab-pane key="WECHAT_PAYMENT" title="微信支付设置">
        <a-col :span="24" >
          <a-form
            ref="wechatFormRef"
            :model="payFormData.wechatForm"
            layout="horizontal"
            auto-label-width
          >
            <a-form-item label="appId" field="appId">
              <a-input
                v-model="payFormData.wechatForm.appId"
                type="text"
                :style="{ width: '65%' }"
              />
              <p class="mark">*APP应用 AppID 非必填</p>
            </a-form-item>
            <a-form-item label="mpAppId" field="mpAppId">
              <a-input
                v-model="payFormData.wechatForm.mpAppId"
                type="text"
                :style="{ width: '65%' }"
              />
              <p class="mark">*小程序 AppID 非必填</p>
            </a-form-item>
            <a-form-item label="serviceAppId" field="serviceAppId">
              <a-input
                v-model="payFormData.wechatForm.serviceAppId"
                type="text"
                :style="{ width: '65%' }"
              />
              <p class="mark">*服务号 AppID 非必填</p>
            </a-form-item>
            <a-form-item
              label="mchId"
              field="mchId"
              :rules="[REQUIRED]"
              
            >
              <a-input v-model="payFormData.wechatForm.mchId" type="text" :style="{ width: '65%' }"/>
            </a-form-item>
            <a-form-item label="商户名称" field="mchName" :rules="[REQUIRED]" style="width: 100%">
              <a-input v-model="payFormData.wechatForm.mchName" type="text" :style="{ width: '65%' }"/>
            </a-form-item>
            <a-form-item label="subMchId" field="subMchId" :rules="[REQUIRED]" style="width: 100%">
              <a-input v-model="payFormData.wechatForm.subMchId" type="text" :style="{ width: '65%' }"/>
              <p class="mark">*平台自建子商户号, 用于充值类业务直接将款项打入平台子商户 必填</p>
            </a-form-item>
            
            <a-form-item label="apiKey3" field="apiKey3" :rules="[REQUIRED]">
              <a-input v-model="payFormData.wechatForm.apiKey3" type="text" :style="{ width: '65%' }"/>
            </a-form-item>
            <a-form-item
              label="apiclient_cert_p12"
              field="apiclient_cert_p12"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="payFormData.wechatForm.apiclient_cert_p12"
                type="text"
                :style="{ width: '65%' }"
              />
            </a-form-item>
            <a-form-item
              label="apiclient_cert_pem"
              field="apiclient_cert_pem"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="payFormData.wechatForm.apiclient_cert_pem"
                type="text"
                :style="{ width: '65%' }"
              />
            </a-form-item>
            <a-form-item
              label="apiclient_key"
              field="apiclient_key"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="payFormData.wechatForm.apiclient_key"
                type="text"
                :style="{ width: '65%' }"
              />
            </a-form-item>
            <a-form-item
              label="serialNumber"
              field="serialNumber"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="payFormData.wechatForm.serialNumber"
                type="text"
                :style="{ width: '65%' }"
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="wechatFormSubmit">保存</a-button>
            </a-form-item>
          </a-form>
        </a-col>
      </a-tab-pane>
    </a-tabs>
  </a-card>
</template>

<script setup lang="ts">
  import { getSetting, setSetting } from '@/api/index';
import { getPaymentSupportForm } from '@/api/setting';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import getAssetsImages from '@/utils/assetsImages';
import { REQUIRED } from '@/utils/validator';
import { Message } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { onMounted, reactive, ref } from 'vue';

  //  获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const alipayFormRef = ref<FormInstance>();
  const wechatFormRef = ref<FormInstance>();
  const componentKey = ref(0);
  // 强制渲染
  const forceRerender = () => {
    componentKey.value += 1;
  };
  interface formInterface {
    way: any;
    payType: string;
    paymentSupportForm: Array<any>;
    supportForm: any;
    payWay: any;
    alipayForm: any;
    wechatForm: any;
  }
  // 数据集
  const payFormData: formInterface = reactive({
    way: {
      // 类型
      APP: '移动应用端',
      H5: '移动端',
      WECHAT_MP: '小程序端',
      PC: 'PC端',
    },
    payType: 'PAYMENT_SUPPORT',
    paymentSupportForm: [], // 表单数据
    supportForm: {}, // 支持的支付方式
    payWay: {
      // 支付方式
      ALIPAY: '支付宝支付',
      WECHAT_PARTNER: '微信支付',
      WALLET: '余额支付',
    },
    alipayForm: {
      appId: '',
      certPath: '',
      alipayPublicCertPath: '',
      privateKey: '',
      rootCertPath: '',
    }, // 支付宝支付设置表单
    wechatForm: {
      appId: '',
      mpAppId: '',
      serviceAppId: '',
      mchId: '',
      apiKey3: '',
      subMchId: '',
      mchName: '', 
      apiclient_cert_p12: '',
      apiclient_cert_pem: '',
      apiclient_key: '',
      serialNumber: '',
    }, // 微信支付设置表单
  });

  // 进入页面请求第一个配置
  const getSettingData = async () => {
    const res = await getSetting(payFormData.payType);
    if (payFormData.payType == 'PAYMENT_SUPPORT') {
      // 支付开启/关闭
      // payFormData.paymentSupportForm = [
      //   {client: "H5", supports: ["WECHAT"]},
      //   {client: "PC", supports: ["WECHAT"]},
      //   {client: "WECHAT_MP", supports: ["WECHAT"]},
      //   {client: "APP", supports: ["WECHAT"]},
      // ];
      if (res.data.success) {
        payFormData.paymentSupportForm = res.data.result.paymentSupportItems;
      }
    } else if (payFormData.payType == 'ALIPAY_PAYMENT') {
      // 支付宝支付设置
      // payFormData.alipayForm = {
      //   alipayPublicCertPath:"/home/crt/lili-alipay/alipayCertPublicKey_RSA2.crt",
      //   appId:"appId",
      //   certPath:"/home/crt/lili-alipay/appCertPublicKey_2021002107649773.crt",
      //   privateKey:"/home/crt/lili-alipay/appCertPublicKey_2021002107649773.crt/home/crt/lili-alipay/appCertPublicKey_2021002107649773.crt",
      //   rootCertPath:"/home/crt/lili-alipay/alipayRootCert.crt",
      // }
      if (res.data.success) {
        payFormData.alipayForm = res.data.result;
      }
    } else if (payFormData.payType == 'WECHAT_PAYMENT') {
      // 微信支付设置
      // payFormData.wechatForm = {
      //   apiKey3:"GratMalln12j3bn21312y983798HNH27",
      //   apiclient_cert_p12:"/home/source/crt/wechat/apiclient_cert.p12",
      //   apiclient_cert_pem:"/home/source/crt/wechat/apiclient_cert.pem",
      //   apiclient_key:"/home/source/crt/wechat/apiclient_key.pem",
      //   mchId:"1647783275",
      //   serialNumber:"6F009B50FCC22FD9B3FC816AD8C3E68AA1B22383",
      //   serviceAppId:"wx6cfbe6e0ace12ce8",
      // }
      if (res.data.success) {
        payFormData.wechatForm = res.data.result;
      }
    }
  };

  // 支付设置tab栏切换
  const clickpatTab = (name: any) => {
    payFormData.payType = name;
    getSettingData();
  };
  // 支持的支付方式
  const init = async () => {
    const res = await getPaymentSupportForm();
    if (res.data.success) {
      payFormData.supportForm = res.data.result;
      
      // 排除payment
      payFormData.supportForm.payments = payFormData.supportForm.payments.filter((item:string)=>{
        return item !== 'WECHAT'
      })
    
    }
  };
  // 保存设置
  const setupSetting = async () => {
    setSetting(payFormData.payType, {
      paymentSupportItems: payFormData.paymentSupportForm,
    }).then(res => {
      if (res.data.success) {
        Message.success('保存成功！');
      } else {
        Message.error('保存失败！');
      }
      init();
      getSettingData();
    });
  };
  // 修改支付设置
  const handleChangePayType = (val: any, event: any): void => {
    modal.confirm({
      title: '修改支付设置',
      content: `您是否修改此项？`,
      alignCenter: false,
      onOk: async () => {
        setupSetting();
      },
      onCancel: async () => {
        getSettingData();
        // 强制渲染
        // forceRerender();
      },
    });
  };
  // 支付宝支付设置 保存
  const alipayFormSubmit = async () => {
    const auth = await alipayFormRef.value?.validate();
    if (!auth) {
      setSetting(payFormData.payType, payFormData.alipayForm).then(res => {
        if (res.data.success) {
          Message.success('保存成功！');
        } else {
          Message.error('保存失败！');
        }
        getSettingData();
      })
    }
  };
  // 微信支付设置 保存
  const wechatFormSubmit = async () => {
    const auth = await wechatFormRef.value?.validate();
    if (!auth) {
      setSetting(payFormData.payType, payFormData.wechatForm).then(res => {
        if (res.data.success) {
          Message.success('保存成功！');
        } else {
          Message.error('保存失败！');
        }
        getSettingData();
      });
    }
  };
  // 初始化
  onMounted(() => {
    init();
    getSettingData();
  });
</script>

<style scoped lang="less">
  .auth-item {
    width: 300px;
    border: 1px solid #e8eaec;
    padding: 0 16px;
    box-sizing: border-box;
    margin: 10px 20px 0 0;
    border-radius: 4px;
    &:hover {
      box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.1);
      transition-delay: 0.3s;
      transition: all 0.2s;
    }
  }
  .icon-item {
    width: 100%;
    padding: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }
  .ivu-form-item {
    display: flex;

    align-items: center;
  }
  .ivu-row {
    width: 100%;
  }
  .icon {
    width: 100px;
    height: 100px;
  }
  .pay-title {
    text-align: center;
    margin: 10px 0 20px;
  }
  .pay-list {
    display: flex;
    justify-content: center;
    padding-bottom: 10px;
  }
  .mark {
    color: red;
    font-size: 12px;
    text-align: right;
    width: 30%;
  }
</style>
